#include "HashTable.h"
#include <iostream>
using namespace std;

int HashTable::Hash(char *functionName)
{
	char *p = functionName;
	int hashValue=0;
	for(;*p!='\0';p++)
	{
		int various = *p - 'a';
		hashValue = (hashValue+various*various*various*various)%1024;
	}
	return hashValue;
}

int HashTable::InternalHash(char *functionName)
{
	char *p = functionName;
	int hashValue=0;
	for(;*p!='\0';p++)
	{
		int various = abs(*p - 'a');
		hashValue = (hashValue+various*various*various)%2048;
	}
	return hashValue;
}



void HashTable::HashDump()
{
	for(int i=0;i<1024;i++)
	{
		if(table[i].next!=NULL)
		{
			hNode *p = table[i].next;

			for(;p!=NULL;p=p->next)
			{
				cout<<i<<":"<<p->name<<endl;
			}
		}
	}
}

bool HashTable::HashStringCompare(char *firstString,char *secondString)
{
	char *pFirst = firstString;
	char *pSecond = secondString;

	for(;(*pFirst!='\0')&&(*pSecond!='\0');pFirst++,pSecond++)
	{
		if(*pFirst!=*pSecond)
		{
			return false;
		}
	}
	return true;
}


Result HashTable::Insert(char *functionName)
{
	int index = Hash(functionName);
	int iHashValue = InternalHash(functionName);
	hNode *p=table[index].next;
	hNode *variousPointer;
	variousPointer = new hNode;
	variousPointer->next=NULL;
	variousPointer->previous=NULL;
	variousPointer->HashValue = index;
	variousPointer->name = functionName;
	variousPointer->InternalHashValue = iHashValue;

	if(table[index].next==NULL)
	{
		table[index].next = variousPointer;
	}
	else
	{
		p = table[index].next;
		for(;p!=NULL;p = p->next)
		{
			if(p->InternalHashValue==variousPointer->InternalHashValue)
			{
				if(HashStringCompare(p->name,variousPointer->name) == true)
				{
					return EXIST;
				}
			}
		}
		p->next = variousPointer;
		p->next->previous = p;
	}
	return SUCCESS;
}

HashTable::~HashTable()
{
	delete[] table;
}